package com.easy.service.impl;

import com.easy.bean.UserAccount;
import com.easy.mapper.UserAccountDao;
import com.easy.service.PasswordResetService;
import com.easy.util.EmailUtil;
import com.easy.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class PasswordResetServiceImpl implements PasswordResetService {

    private static final Map<String, String> EMAIL_CODE_STORE = new ConcurrentHashMap<>();
    private static final Map<String, String> EMAIL_CODE_USER = new ConcurrentHashMap<>();

    @Autowired
    private UserAccountDao userAccountDao;

    @Override
    public void sendVerificationCode(String email) {
        String code = String.format("%06d", (int) (Math.random() * 1000000));
        EMAIL_CODE_STORE.put(email, code);
        EmailUtil.sendEmail(email, code);
    }

    @Override
    public boolean verifyCode(String email, String code) {
        String storedCode = EMAIL_CODE_STORE.get(email);
        if (storedCode != null && storedCode.equals(code)) {
            EMAIL_CODE_USER.put(email, code); // 验证成功标记
            EMAIL_CODE_STORE.remove(email);
            return true;
        }
        return false;
    }

    @Override
    public boolean resetPassword(String email, String newPassword) {
        // 1. 验证邮箱是否已经验证通过
        String verifiedCode = EMAIL_CODE_USER.get(email);
        if (verifiedCode == null) {
            return false; // 未验证
        }

        // 2. 获取用户
        UserAccount userAccount = userAccountDao.getByEmail(email);
        if (userAccount == null) {
            return false; // 用户不存在
        }

        // 3. 加密新密码
        String encryptedPassword = PasswordUtil.encryptPassword(newPassword);
        userAccount.setPassword_hash(encryptedPassword);
        userAccount.setPassword(null); // 不保存明文

        // 4. 更新数据库
        int result = userAccountDao.edit(userAccount);

        // 5. 移除验证记录
        EMAIL_CODE_USER.remove(email);

        return result > 0;
    }
}
